package com.combetter.changxing.net;

import android.support.annotation.WorkerThread;

import com.combetter.changxing.Config;
import com.combetter.changxing.util.LogUtil;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by mark.fan on 2018/5/3.
 */

public class HttpRequest {
    private Retrofit mRetrofit;

    private HttpRequest sInstance;
    private static final long TIMEOUT = 30;

    static class Holder {
        static HttpRequest httpRequest = new HttpRequest();
    }

    // Retrofit是基于OkHttpClient的，可以创建一个OkHttpClient进行一些配置
    private OkHttpClient httpClient = new OkHttpClient.Builder()
            // 添加通用的Header
            .addInterceptor(chain -> {
                Request.Builder builder = chain.request().newBuilder();
                //  builder.addHeader("token", "123");
                return chain.proceed(builder.build());
            })
            /*
            这里可以添加一个HttpLoggingInterceptor，因为Retrofit封装好了从Http请求到解析，
            出了bug很难找出来问题，添加HttpLoggingInterceptor拦截器方便调试接口
             */
            .addInterceptor(new HttpLoggingInterceptor(message ->
                    LogUtil.e(message))
                    .setLevel(HttpLoggingInterceptor.Level.BASIC))
            .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(TIMEOUT, TimeUnit.SECONDS)
            .build();

    private HttpRequest() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(Config.URL_BASE)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient)
                .build();
    }



    public static HttpRequest getInstance() {
        return Holder.httpRequest;
    }

    @WorkerThread
    public <T> T createService(Class<T> service) {
        return mRetrofit.create(service);
    }

}
